package com.lotea.android.andreaditlater.io;

import java.util.ArrayList;

import org.apache.http.HttpStatus;

import android.content.Context;

import com.lotea.android.andreaditlater.utils.Log;

public class APIHelper {

	public static final int STATE_ALL = 0;
	public static final int STATE_READ = 1;
	public static final int STATE_UNREAD = 2;

	public static final int TAGS_ON = 1;
	public static final int TAGS_OFF = 0;

	private ConnectionClient mConnectionClient;
	private JSONToDb mJsonToDb;
	private String mApiKey;

	public APIHelper(Context context, String apiKey) {
		mApiKey = apiKey;
		mConnectionClient = new ConnectionClient();
		mJsonToDb = new JSONToDb(context);
	}

	public boolean auth(String user, String pass) {
		try {
			final String url = buildUrl(API.URL,
					API.Methods.Authentication.URL, new String[] {
							API.Methods.Authentication.Params.API_KEY,
							API.Methods.Authentication.Params.USERNAME,
							API.Methods.Authentication.Params.PASSWORD },
					new String[] { mApiKey, user, pass });

			APIResponse response = mConnectionClient.getResponseFromURL(url);
			return response.getStatus() == HttpStatus.SC_OK;

		} catch (Exception e) {
			Log.e("Authenticating error", e);
		}

		return false;
	}

	public void getList(String user, String pass, long since, int state) {

		ArrayList<String> paramKeys = new ArrayList<String>();
		paramKeys.add(API.Methods.Authentication.Params.API_KEY);
		paramKeys.add(API.Methods.Authentication.Params.USERNAME);
		paramKeys.add(API.Methods.Authentication.Params.PASSWORD);
		paramKeys.add(API.Methods.Get.Params.SINCE);
		paramKeys.add(API.Methods.Get.Params.TAGS);

		ArrayList<String> paramValues = new ArrayList<String>();
		paramValues.add(mApiKey);
		paramValues.add(user);
		paramValues.add(pass);
		paramValues.add(Long.toString(since));
		paramValues.add(Integer.toString(TAGS_ON));

		if (state != STATE_ALL) {
			paramKeys.add(API.Methods.Get.Params.STATE);
		}

		switch (state) {
		case STATE_READ:
			paramValues.add(API.Methods.Get.ParamValues.STATE_READ);
			break;
		case STATE_UNREAD:
			paramValues.add(API.Methods.Get.ParamValues.STATE_UNREAD);
			break;
		}

		try {
			final String url = buildUrl(API.URL, API.Methods.Get.URL, paramKeys
					.toArray(new String[paramKeys.size()]),
					(String[]) paramValues
							.toArray(new String[paramKeys.size()]));

			APIResponse response = mConnectionClient.getResponseFromURL(url);
			if (response.getStatus() == HttpStatus.SC_OK
					&& response.getData().length() > 0) {
				mJsonToDb.parseItemsIntoDb(response.getData());
			}

		} catch (Exception e) {
			Log.e("Getting list error", e);
		}
	}

	private String buildUrl(String baseUrl, String method, String[] paramKeys,
			String[] paramValues) throws Exception {
		StringBuilder builder;
		builder = new StringBuilder();
		builder.append(baseUrl);
		builder.append(method);

		if (paramKeys != null && paramValues != null) {
			if (paramKeys.length == paramValues.length) {
				builder.append('?');

				for (int i = 0; i < paramKeys.length; i++) {
					builder.append(paramKeys[i]);
					builder.append('=');
					builder.append(paramValues[i]);

					if (i < paramKeys.length - 1) {
						builder.append('&');
					}
				}

			} else {
				throw new Exception(
						"Error. Missing parameters. 'paramKeys' and 'paramValues' must have the same length");
			}

		} else {
			throw new Exception(
					"Error. Missing parameters. 'paramKeys' and 'paramValues' can't be void when the other one isn't");
		}

		return builder.toString();
	}
}
